package thesis.javaclass;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class ConfirmServer implements Runnable {

	private static final int PORT = 1243;
	private static ServerSocket serverSocket;

	private static Socket socket = null;

	public void run() {
		try {
			serverSocket = new ServerSocket(PORT);
		} catch (IOException ioex) {
			System.out.println("Unable to set up port ....");
			System.exit(1);
		}
		do {
			try {
				socket = serverSocket.accept();
				TaxiHandler handler = new TaxiHandler(socket);
				Thread t = new Thread(handler, "Port " + socket.getPort());
				t.start();
			} catch (IOException e) {

				e.printStackTrace();
			}

		} while (true);
	}

	class TaxiHandler implements Runnable {

		private Socket link = null;
		private BufferedReader input = null;

		public TaxiHandler(Socket socket) {
			this.link = socket;
		}

		@Override
		public void run() {
			try {
				input = new BufferedReader(new InputStreamReader(
						link.getInputStream()));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			String message = "";
			try {
				message = input.readLine();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			// Singleton.getInstance();
			System.out.println("message : " + message);
			String[] data = parseMessage(message);

			int status = Integer.parseInt(data[2]);
			String phone = data[1];
			String imei = data[0];
			if (status == StatusCode.ACCEPT_STATUS) {
				ServiceList.get(phone).setSelectedImei(imei);
			} else if (status == StatusCode.PICKED_UP_STATUS) {
				ServiceList.get(phone).updateService(phone, status);
				ServiceList.setFree(imei);
			} else if (status == StatusCode.FINISH_STATUS) {
				ServiceList.get(phone).updateService(phone, status);
			} else if (status == StatusCode.CAN_NOT_PICKUP_STATUS) {
				ServiceList.get(phone).updateService(phone, status);
				ServiceList.setFree(imei);
			}

			try {
				link.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	private String[] parseMessage(String mess) {
		return mess.split(",");
	}

}
